/* 
*根据用户的权限，筛选菜单



*/

export  const getUserMenus = function (menus,role){
    let resMenus = []
   for (const item of menus) {
    if (judegMenusAuth(item, role)) {
        if (item?.children && item.children.length > 0) {
            let childrenMenus = {...item}
            childrenMenus.children = getUserMenus(item.children)
            
        } else {
            resMenus.push(item)
        }
    }
   }
   return resMenus
}
/* 
* @params(对权限控制 ，menu 每一个菜单， 权限字段， role 用户的角色表) 
 */
function judegMenusAuth(menu, field = 'role', role=["普通管理员"]){
    let flag = false
   if (menu.meta?.role && menu.meta?.role.length > 0) {
    flag = role.some(item =>menu.meta?.role.includes(item) )
   } 
   return flag
}

/*筛选菜单 
 */
export const filterMenus =  function (menus=[], roles=["普通管理员"]){
    let res = []
    for (const menu of menus) {
        if (judegAuth(menu, roles)) {
            if (menu.children && menu.children.length>0) {
                let obj = {...menu}
                obj.children = filterMenus(menu.children,roles)
               if (obj.children.length>0) {
                res.push(obj)
               }
            }else {
                res.push(menu)
            }
        }
    }
    return res
}

function judegAuth(menu, roles){
    let flag =false
    if (!menu.roles) {
        flag = true
    } else {
        flag =  roles.some(item=>{
            return menu.roles.includes(item)
         })
    }
    
    return flag
}